package com.ztesoft.book.common.utils.encrypt;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.ztesoft.book.common.utils.exception.ExUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Description 国密算法 ECB
 * @Author YangFan
 * @Date 2021-06-22 17:19
 */
@Slf4j
@Component
public final class AesEncryptSm4Util {

    private AesEncryptSm4Util() {
    }

    /**
     * 密钥 注：必须是16位
     */
    private static String secretKey = "ZTESOFT2021_BOOK";


    public static String encrypt(String data) {
        try {
            if (StrUtil.isBlank(data)) {
                return null;
            }
            SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", secretKey.getBytes(StandardCharsets.UTF_8));
            return sm4.encryptHex(data);
        }
        catch (Exception e) {
            log.error("SM4国密加密出现UnsupportedEncodingException异常", e);
            ExUtil.throwEx("SM4国密加密出现UnsupportedEncodingException异常:" + e.getMessage());
            return null;
        }
    }

    public static String desEncrypt(String data) {
        try {
            if (StrUtil.isBlank(data)) {
                return null;
            }
            SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", secretKey.getBytes(StandardCharsets.UTF_8));
            return sm4.decryptStr(data);
        }
        catch (Exception e) {
            log.error("SM4国密解密出现UnsupportedEncodingException异常", e);
            ExUtil.throwEx("SM4国密解密出现UnsupportedEncodingException异常:" + e.getMessage());
            return null;
        }
    }


}
